package com.skytech.tax.customsdatawarehouse.singlewindow.taxhandle.domain.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.skytech.tax.customsdatawarehouse.common.util.SecurityUtil;
import com.skytech.tax.customsdatawarehouse.singlewindow.taxhandle.domain.dao.GuaranteeLetterAmountDao;
import com.skytech.tax.customsdatawarehouse.singlewindow.taxhandle.domain.entity.GuaranteeLetterAmount;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GuaranteeLetterAmountService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GuaranteeLetterAmountService.class);

    @Value("${customsdatawarehouse.token}")
    private String token;

    @Resource
    private GuaranteeLetterAmountDao guaranteeLetterAmountDao;

    public void save(String guaranteeLetterAmt) {
        if (StringUtils.isEmpty(guaranteeLetterAmt)) return;
        String guaranteeLetterAmtText = SecurityUtil.decrypt3DES(token, guaranteeLetterAmt);
        try {
            JSONObject data = JSON.parseObject(guaranteeLetterAmtText);
            if (data == null) return;
            String socialCreditCode = data.getString("socialCreditCode");
            JSONArray guaranteeLetterAmtArr = data.getJSONArray("guaranteeLetterAmt");
            if (CollectionUtils.isEmpty(guaranteeLetterAmtArr)) return;

            //电子税单列表拆分并存储
            List<GuaranteeLetterAmount> guaranteeLetterAmtList = new ArrayList<>();
            for (int i = 0; i < guaranteeLetterAmtArr.size(); i++) {
                JSONObject item = guaranteeLetterAmtArr.getJSONObject(i);
                guaranteeLetterAmtList.add(new GuaranteeLetterAmount(socialCreditCode, item));
            }
            if (CollectionUtils.isEmpty(guaranteeLetterAmtList)) return;

            guaranteeLetterAmountDao.deleteBy(guaranteeLetterAmtList.stream().map(GuaranteeLetterAmount::getSwAmountId).collect(Collectors.toList()));

            guaranteeLetterAmountDao.save(guaranteeLetterAmtList);
        } catch (Exception e) {
            LOGGER.error("保存保函额度变动信息错误", e);
        }
    }
}
